use serde::{Deserialize, Serialize};
use validator::Validate;
use crate::dto::point_dto::PointDto;
use crate::entity::pointgroups;
use crate::entity::pointgroups::Model;
use crate::entity::prelude::Pointgroups;

#[derive(Debug, Validate, Deserialize, Serialize, Clone)]
pub struct BasePointGroupDto {
    pub name: String,
    pub description: String,
    pub isPrivate: bool,
    pub isOverLimit: bool,
    pub groupType: i32,
    pub groupPermission: Option<i32>,
}

#[derive(Debug, Validate, Deserialize, Serialize, Clone)]
pub struct PointGroupDto {
    pub id: i32,
    #[serde(flatten)]
    pub base: BasePointGroupDto,
    pub points : Vec<PointDto>,
}

impl From<Model> for PointGroupDto {
    fn from(value: Model) -> Self {
        PointGroupDto {
            id: value.id,
            base: BasePointGroupDto {
                name: value.name,
                description: value.description,
                isPrivate: value.is_private == 1,
                isOverLimit: value.is_over_limit == 1,
                groupType: value.group_type,
                groupPermission: Some(value.group_permission),
            },
            points: vec![],
        }
    }
}

#[derive(Debug, Validate, Deserialize, Serialize, Clone)]
pub struct AddPointGroupDto {
    #[serde(flatten)]
    pub base: BasePointGroupDto,
}

#[derive(Debug, Validate, Deserialize, Serialize, Clone)]
pub struct UpdatePointGroupDto {
    pub id: i32,
    #[serde(flatten)]
    pub base: BasePointGroupDto,
    pub points: Vec<PointDto>,
}


impl Into<Model> for AddPointGroupDto {
    fn into(self) -> Model {
        Model {
            id: 0,
            name: self.base.name,
            description: self.base.description,
            is_private: i8::from(self.base.isPrivate),
            is_over_limit: i8::from(self.base.isOverLimit),
            over_limit_expression: None,
            group_type: self.base.groupType,
            group_permission: if self.base.groupPermission.is_none() { 0 } else { self.base.groupPermission.unwrap() },
        }
    }
}
impl Into<Model> for BasePointGroupDto {
    fn into(self) -> Model {
        Model {
            id: 0,
            name: self.name,
            description: self.description,
            is_private: i8::from(self.isPrivate),
            is_over_limit: i8::from(self.isOverLimit),
            over_limit_expression: None,
            group_type: self.groupType,
            group_permission: if self.groupPermission.is_none() { 0 } else { self.groupPermission.unwrap() },
        }
    }
}
